#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>

void createTable(MYSQL *conn) {
    if (mysql_query(conn, "CREATE TABLE students (id INT, name VARCHAR(20), age INT)")) {
        printf("Table creation failed: %s\n", mysql_error(conn));
    } else {
        printf("Table created successfully\n");
    }
}

void insertData(MYSQL *conn, int id, const char *name, int age) {
    char query[100];
    sprintf(query, "INSERT INTO students VALUES (%d, '%s', %d)", id, name, age);
    if (mysql_query(conn, query)) {
        printf("Data insertion failed: %s\n", mysql_error(conn));
    } else {
        printf("Data inserted successfully\n");
    }
}

void queryData(MYSQL *conn) {
    if (mysql_query(conn, "SELECT * FROM students")) {
        printf("Query failed: %s\n", mysql_error(conn));
        return;
    }

    MYSQL_RES *result = mysql_store_result(conn);
    MYSQL_ROW row;

    printf("ID\tName\tAge\n");
    while ((row = mysql_fetch_row(result))) {
        printf("%s\t%s\t%s\n", row[0], row[1], row[2]);
    }
    mysql_free_result(result);
}

int main() {
    MYSQL *conn = mysql_init(NULL);
    if (conn == NULL) {
        printf("mysql_init failed\n");
        return 1;
    }

    // 使用你的密码和数据库名称连接到MySQL
    if (mysql_real_connect(conn, "localhost", "root", "1275279401", "test_db", 0, NULL, 0) == NULL) {
        printf("mysql_real_connect failed: %s\n", mysql_error(conn));
        mysql_close(conn);
        return 1;
    }

    createTable(conn);
    insertData(conn, 1, "Alice", 20);
    insertData(conn, 2, "Bob", 22);
    queryData(conn);

    mysql_close(conn);
    return 0;
}
